/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* _buildTree(vector<int>& preorder, int& rootsignal, vector<int>& inorder, int front, int back)
    {
        if (front > back || rootsignal >= preorder.size())
            return nullptr;
        TreeNode* root = new TreeNode;
        root->val = preorder[rootsignal];
        rootsignal++;
        int rooti = front;
        while (rooti <= back)
        {
            if (root->val == inorder[rooti])
                break;
            else
                rooti++;
        }



        root->left = _buildTree(preorder, rootsignal, inorder, front, rooti - 1);

        root->right = _buildTree(preorder, rootsignal, inorder, rooti + 1, back);

        return root;

    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int i = 0;
        TreeNode* root = _buildTree(preorder, i, inorder, 0, inorder.size() - 1);
        return root;
    }
};